import { Gender } from "@mallfoundry/keystone/identity"
import { Member } from "@mallfoundry/store/member"
import { Button, DatePicker, Form, Input, Radio, Space } from "antd"
import * as dayjs from "dayjs"
import * as _ from "lodash"
import * as React from "react"
import { useEffect } from "react"

interface MemberFormProps {
  idReadonly?: boolean
  loading: boolean
  member: Member
  onFinish?: (member: Member) => void
  onCancel?: () => void
}

export default function MemberForm(props: MemberFormProps) {
  const { loading, idReadonly, member, onFinish: finish, onCancel } = props
  const layout = { labelCol: { span: 2 }, wrapperCol: { span: 4 } }
  const tailLayout = { wrapperCol: { offset: 2, span: 16 } }

  const [form] = Form.useForm()

  const onFinish = (values: any) => {
    if (_.isFunction(finish)) {

      finish(_.assign(new Member(), member, values,
        _.isEmpty(values.birthdate) ? {}
          : { birthdate: values.birthdate.format("YYYY-MM-DD") }))
    }
  }

  useEffect(() => {
    form.setFieldsValue(_.assign(member, { birthdate: dayjs(member.birthdate) }))
  }, [form, member])

  return (
    <Form {...layout} form={form} initialValues={{ gender: Gender.Unknown }} onFinish={onFinish}>
      <Form.Item label="会员账号" name="id">
        {idReadonly ? <span className="ant-form-text">{member.id}</span> : <Input/>}
      </Form.Item>
      <Form.Item label="姓名" name="nickname">
        <Input/>
      </Form.Item>
      <Form.Item label="性别" name="gender">
        <Radio.Group>
          <Radio value={Gender.Male}>男</Radio>
          <Radio value={Gender.Female}>女</Radio>
          <Radio value={Gender.Unknown}>保密</Radio>
        </Radio.Group>
      </Form.Item>
      <Form.Item label="生日" name="birthdate">
        <DatePicker style={{ width: "100%" }}/>
      </Form.Item>
      <Form.Item label="备注" name="notes">
        <Input.TextArea autoSize={{ minRows: 4, maxRows: 6 }}/>
      </Form.Item>
      <Form.Item {...tailLayout}>
        <Space>
          <Button type="primary" htmlType="submit" loading={loading}>保存</Button>
          <Button htmlType="button" onClick={onCancel}>取消</Button>
        </Space>
      </Form.Item>
    </Form>
  )
}
